package LeetCode.NumOffer;

import java.util.Arrays;

/**
 * 螺旋矩阵
 * @author lumin
 * @date 2022/04/14 22:44
 **/
public class NumOffer29 {
    public static int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0];
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int[] arr = new int[row * col];
        int i = 0;
        int j = 0;
        int beginR = 0;
        int beginC = 0;
        int Aindex = 0;
        while(Aindex < arr.length){
            while(Aindex < arr.length && j < col - beginC){
                arr[Aindex] = matrix[i][j];
                Aindex++;
                j++;
            }
            j--;
            i++;
            while (Aindex < arr.length && i < row - beginR){
                arr[Aindex] = matrix[i][j];
                Aindex++;
                i++;
            }
            i--;
            j--;
            while (Aindex < arr.length && j >= beginC){
                arr[Aindex] = matrix[i][j];
                Aindex++;
                j--;
            }
            beginC++;
            j++;
            i--;
            while (Aindex < arr.length && i > beginR){
                arr[Aindex] = matrix[i][j];
                Aindex++;
                i--;
            }
            beginR++;
            i++;
            j++;
        }
        return arr;
    }

    public static void main(String[] args) {
        int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
        System.out.println(Arrays.toString(spiralOrder(arr)));
    }
}